package com.socket.nio.demos;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @auther zhangwj
 * @date 2020/6/17 2:31 下午
 */
public class SocketChannelDemo {

    public static void getServer(int port) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(true);
        serverSocketChannel.bind(new InetSocketAddress(port));
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        while (true) {
            SocketChannel socketChannel = serverSocketChannel.accept();
            int size = socketChannel.read(byteBuffer);
            while (size > 0) {
                byteBuffer.flip();
                System.out.println(byteBuffer.get());
            }
            socketChannel.close();
        }

    }

    public static void main(String[] args) throws IOException {
        SocketChannelDemo.getServer(8080);
    }
}
